import logging
from flask import current_app, render_template, jsonify, session, request
from info.utits.response_code import RET
from info import redis_store, constants
from . import index_bp
from flask import g
from info.models import User, News, Category
from info.utits.common import  user_login_data



@index_bp.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')
@index_bp.route('/')
@user_login_data

def index():
    user=g.user

    # -------------用户数据查询-------------

    # user_id=session.get("user_id")
    # user=None #  type:User
    # if  user_id:
    #     try:
    #         user=User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    #         return jsonify(errno=RET.DBERR,errmsg="查询用户对象异常")

    # ----------------点击排行新闻收藏------------
    try:
        news_rank_list=News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="点击排行数据库查询异常")
    news_rank_dict_list=[]
    for news_obj in news_rank_list:
        news_dict=news_obj.to_dict()
        news_rank_dict_list.append(news_dict)


    # ---------------新闻分类数据查询-----------------
    try:
        categories=Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="分类数据查询失败")
    category_dict_list=[]
    for category_by in categories:
        category_dict_list.append(category_by.to_dict())


    data ={
        "user_info":user.to_dict() if user else None,
        "news_rank_list":news_rank_dict_list,
        "categories":category_dict_list
    }
    return render_template('news/index.html',data=data)


@index_bp.route('/news_list')
def get_news_list():
    """
    获取参数
        分类id，当前页码，每一页多少条数据per_page=10默认
    校验参数
        非空判断
        整形强制类型转换
    逻辑处理
        分页查询
        对象列表转字典裂变
    返回值
        返回data
    :return:
    """
    param_dict=request.args
    cid=param_dict.get('cid',"1")
    page=param_dict.get('page',"1")
    per_page=param_dict.get("per_page","10")
    if not cid:
        return jsonify(errno=RET.PARAMERR,errmsg="参数不足")
    try:
        cid=int(cid)
        page=int(page)
        per_page=int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        jsonify(errno=RET.PARAMERR,errmsg="参数格式错误")
    filters=[]
    if cid !=1:
        filters.append(News.category_id == cid)

    try:
        paginate =News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
        # 当前页码所有的数据
        items = paginate.items
        # 当前页码
        current_page=paginate.page
        # 总页码
        total_page=paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询的新闻列表异常")
    news_dict_list=[]
    for news in items if items else []:
        news_dict_list.append(news.to_dict())
    data = {
        "news_list":news_dict_list,
        "current_page":current_page,
        "total_page":total_page
    }
    return jsonify(errno=RET.OK,errmsg="查询新闻列表成功",data=data)